import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart' as fluwx;

class TestPay extends StatefulWidget {
  @override
  _TestPayState createState() => _TestPayState();
}

class _TestPayState extends State<TestPay> {
  //点击支付选择
  List<BrnCommonActionSheetItem> actions = [];

  //点击分享
  List<BrnShareItem> firstRowList = [];

  //注册微信
  void initWxApi() {
    fluwx.registerWxApi(
      appId: "wx86906bf47492eb6f",
      universalLink: "https://help.wechat.com/app", // https://open.weixin.qq.com         https://help.wechat.com/app
    );
  }


  //微信支付
  Future<void> openWxPay() async {
    //是否安装微信
    bool isInstalled = await fluwx.isWeChatInstalled;
    if (!isInstalled) {
      BrnToast.show("请先安装微信", context);
      return;
    }
    Map payMap =
    {
      "package": "Sign=WXPay",
      "appid": "wx86906bf47492eb6f",
      "sign": "268407DEF89A7211C81171B2B6E7905C",
      "partnerid": "1628778879",
      "prepayId": "wx2409355551171242e0dc22659183230000",
      "nonceStr": "20220724093553410729234",
      "timestamp": "1658626553"
    };
    //调起支付
    fluwx.payWithWeChat(
      appId: payMap["appid"].toString(),
      partnerId: payMap["partnerid"].toString(),
      prepayId: payMap["prepayId"].toString(),
      packageValue: "Sign=WXPay",
      nonceStr: payMap["nonceStr"].toString(),
      timeStamp: int.parse(payMap["timestamp"]),
      sign: payMap["sign"],
    );
    print(payMap["appid"]+"-------------------------------------");
    print(payMap["mch_id"]+"-------------------------------------");
    print(payMap["prepay_id"]+"-------------------------------------");
    print(payMap["nonce_str"]+"-------------------------------------");
    print(payMap["sign"]+"-------------------------------------");

    //监听微信回调
    fluwx.weChatResponseEventHandler.listen((event) {
      if(event.isSuccessful) {
        BrnToast.show("微信支付成功", context);
      } else {
        BrnToast.show("微信支付失败", context);
        print("支付失败打印");
        print(event.errStr);
      }
    });
  }


  //第三方APP微信登录
  void loginWX() {

    //拉取用户信息
    print("微信登录");
    fluwx
        .sendWeChatAuth(scope: "snsapi_userinfo", state: "wechat_sdk_demo_test")
        .then((data) {
      setState(() {
        print("拉取微信用户信息：" + data.toString());
      });
    }).catchError((e) {
      print('weChatLogin  e  $e');
    });

    //监听获取返回值
    fluwx.weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
      if (res is fluwx.WeChatAuthResponse) {
        int errCode = res.errCode;
        //MyLogUtil.d('微信登录返回值：ErrCode :$errCode  code:${res.code}');
        print('微信登录返回值     '+res.code.toString());
        if (errCode == 0) {
          String code = res.code.toString();
          //把微信登录返回的code传给后台，剩下的事就交给后台处理
         // _presenter.getWeChatAccessToken(code);

          print('用户同意授权成功');
        } else if (errCode == -4) {

          print('用户拒绝授权');
        } else if (errCode == -2) {

          print('用户取消授权');
        }
      }
    });



  }














  //多选状态框
  ///标签选择弹框
  void _showMulSelectTagPicker(BuildContext context) {
    List tags = [
      '洗衣机',
      '电视机',
      '电冰箱',
      '双人床',
      '电茶炉',
      '洗手池222',
      '电茶炉333',
      '洗手池3311',
      '洗碗机',
      '挖掘111122机',
      '抽风机',
      '可爱多',
    ];

    List <BrnTagItemBean> items = [];
    for (int i = 0; i < tags.length ;i++){
      String it = tags[i];
      BrnTagItemBean item = BrnTagItemBean(name: it,code: it,index: i, isSelect: true);
      items.add(item);
    }

    BrnMultiSelectTagsPicker(
      context: context,

      //排列样式 默认 平均分配排序
      layoutStyle: BrnMultiSelectTagsLayoutStyle.average,

      //一行多少个 默认4个
      crossAxisCount: 4,

      //最大选中数目 - 不设置 或者设置为0 则可以全选
      maxSelectItemCount: 5,
      onItemClick: (BrnTagItemBean onTapTag, bool isSelect) {
        BrnToast.show(onTapTag.toString(), context);
      },
      onMaxSelectClick: () {
        BrnToast.show('最大数值不能超过5个', context);
      },
      pickerTitleConfig: BrnPickerTitleConfig(
        titleContent: '多选标题',
      ),
      tagPickerConfig: BrnTagsPickerConfig(
        tagItemSource: items,
        tagTitleFontSize: 12,
        chipPadding: EdgeInsets.only(left: 5, right: 5),
        tagTitleColor: Color(0xFF666666),
        tagBackgroudColor: Color(0xffF8F8F8),
        selectedTagBackgroudColor: Color(0x140984F9),
        selectedTagTitleColor: Color(0xFF0984F9),
      ),
      onConfirm: (value) {
        BrnToast.show(value.toString(), context);
      },
      onCancel: () {
        BrnToast.show('点击了取消按钮', context);
      },
      onTagValueGetter: (choice) {
        return choice.name;
      },
    ).show();
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    initWxApi();
    actions.add(
      BrnCommonActionSheetItem(
        '微信支付',
        //desc: '点击后跳转微信支付',
        titleStyle: TextStyle(
          fontSize: 18,
          color: Colors.blue,
        ),
      ),
    );
    actions.add(
      BrnCommonActionSheetItem(
        '支付宝支付',
        // desc: '点击后跳转支付宝支付',
        titleStyle: TextStyle(
          fontSize: 18,
          color: Colors.blue,
        ),
      ),
    );
    // actions.add(
    //   BrnCommonActionSheetItem(
    //     '选项三: 自定义拦截点击事件，点击无效',
    //     desc: '辅助信息',
    //     titleStyle: TextStyle(
    //       fontSize: 16,
    //       color: Color(0xFF999999),
    //     ),
    //     descStyle: TextStyle(
    //       fontSize: 14,
    //       color: Color(0xFF999999),
    //     ),
    //   ),
    // );

    //分享
    firstRowList.add(BrnShareItem(
      BrnShareItemConstants.shareWeiXin,
      canClick: true,
    ));
    firstRowList.add(BrnShareItem(
      BrnShareItemConstants.shareFriend,
      canClick: true,
    ));

  }

  @override
  Widget build(BuildContext context) {
    return ListView(
      children: [
        SizedBox(
          height: 100,
        ),
        InkWell(
          onTap: () {
            // 展示actionSheet
            showModalBottomSheet(
                context: context,
                backgroundColor: Colors.transparent,
                builder: (BuildContext context) {
                  return BrnCommonActionSheet(
                    title: "商品支付",
                    actions: actions,
                    maxTitleLines: 3,
                    clickCallBack: (
                      int index,
                      BrnCommonActionSheetItem actionEle,
                    ) {
                      String title = actionEle.title;
                      BrnToast.show("title: $title, index: $index", context);
                      print("选择了" + index.toString());
                    },
                    onItemClickInterceptor: (
                      int index,
                      BrnCommonActionSheetItem actionEle,
                    ) {
                      // 选项三点击事件被拦截，不作处理
                      if (index == 2) {
                        BrnToast.show("被拦截了", context);
                        return true;
                      }
                      // 其他选项正常
                      return false;
                    },
                  );
                });
          },
          child: Container(
            width: 40,
            height: 100,
            alignment: Alignment.center,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(40), color: Colors.orange),
            child: Text(
              "点击选择支付",
              style: TextStyle(fontSize: 26, fontWeight: FontWeight.w600),
            ),
          ),
        ),
        InkWell(
          onTap: () {
            BrnShareActionSheet actionSheet = new BrnShareActionSheet(
              firstShareChannels: firstRowList,
              clickCallBack: (int section, int index, BrnShareItem shareItem) {
                int channel = shareItem.shareType;
                BrnToast.show("channel: $channel, section: $section, index: $index", context);
              },
              cancelTitle: "点击取消分享", // 取消按钮title可自定义
            );
            actionSheet.show(context);
          },
          child: Container(
            width: 40,
            height: 100,
            alignment: Alignment.center,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(40), color: Colors.orange),
            child: Text(
              "点击分享...",
              style: TextStyle(fontSize: 26, fontWeight: FontWeight.w600),
            ),
          ),
        ),
        InkWell(
          onTap: () {

            String format = 'yyyy年-MM月-dd日';
            BrnPickerTitleConfig pickerTitleConfig = BrnPickerTitleConfig(titleContent: "选择时间范围");
            BrnDateRangePicker.showDatePicker(context,
                isDismissible: false,
                minDateTime: DateTime(2010, 06, 01, 00, 00, 00),
                maxDateTime: DateTime(2029, 07, 24, 23, 59, 59),
                pickerMode: BrnDateTimeRangePickerMode.date,
                minuteDivider: 10,
                pickerTitleConfig: pickerTitleConfig,
                dateFormat: format,
                initialStartDateTime: DateTime(2020, 06, 21, 11, 00, 00),
                initialEndDateTime: DateTime(2020, 06, 23, 10, 00, 00),
                onConfirm: (startDateTime, endDateTime, startlist, endlist) {
                  BrnToast.show(
                      "onConfirm:  $startDateTime   $endDateTime     $startlist     $endlist", context);
                }, onClose: () {
                  print("onClose");
                }, onCancel: () {
                  print("onCancel");
                }, onChange: (startDateTime, endDateTime, startlist, endlist) {
                  BrnToast.show(
                      "onChange:  $startDateTime   $endDateTime     $startlist     $endlist", context);
                });

          },
          child: Container(
            width: 40,
            height: 100,
            alignment: Alignment.center,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(40), color: Colors.orange),
            child: Text(
              "时间选择...",
              style: TextStyle(fontSize: 26, fontWeight: FontWeight.w600),
            ),
          ),
        ),
        InkWell(
          onTap: () {

            _showMulSelectTagPicker(context);

          },
          child: Container(
            width: 40,
            height: 100,
            alignment: Alignment.center,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(40), color: Colors.orange),
            child: Text(
              "多选状态...",
              style: TextStyle(fontSize: 26, fontWeight: FontWeight.w600),
            ),
          ),
        ),
        InkWell(
          onTap: () {
            openWxPay();
          },
          child: Container(
            width: 40,
            height: 100,
            alignment: Alignment.center,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(40), color: Colors.orange),
            child: Text(
              "微信支付...",
              style: TextStyle(fontSize: 26, fontWeight: FontWeight.w600),
            ),
          ),
        ),
        InkWell(
          onTap: () {
            Navigator.of(context).pushNamed("tabbar");
          },
          child: Container(
            width: 30,
            height: 50,
            alignment: Alignment.center,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(30), color: Colors.orange),
            child: Text(
              "跳转测试支付宝支付...",
              style: TextStyle(fontSize: 26, fontWeight: FontWeight.w600),
            ),
          ),
        ),
        InkWell(
          onTap: () {
            loginWX();
          },
          child: Container(
            width: 30,
            height: 50,
            alignment: Alignment.center,
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(30), color: Colors.orange),
            child: Text(
              "微信登录...",
              style: TextStyle(fontSize: 26, fontWeight: FontWeight.w600),
            ),
          ),
        ),
      ],
    );
  }
}
